#pragma once
#include <iostream>
#include <sys/ipc.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <sys/shm.h>
#include <sys/types.h>
#include <string>
#include <unistd.h>
using namespace std;

const char* pathname = "/home/Faiz/daima.biji.boke/Linux/0.code/6-5";
const int proj_id = 0x66;
const int SIZE = 4096;

string ToHex(key_t key)
{
    char buff[1024];
    snprintf(buff,sizeof(buff),"0x%x",key);
    return buff; 
}

key_t GetShmkeyOrDie()
{
    key_t key = ftok(pathname,proj_id);
    if(key < 0)
    {
        cerr << "ftok error,error: " << errno << ", error string: " << strerror(errno) << endl;
        exit(1);
    }
    return key;
}

int CerateShmOrDie(key_t key,int size,int flag)
{
    int shmid = shmget(key,size,flag);
    if(shmid < 0)
    {
        cerr << "shmget error,error: " << errno << ", error string: " << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(key_t key,int size)
{
    return CerateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm(key_t key,int size)
{
    return CerateShmOrDie(key, size, IPC_CREAT);
}

void DeleteShm(int shmid)
{
    int n = shmctl(shmid,IPC_RMID,nullptr);
    if(n < 0)
    {
        cerr << "shmctl error " << endl;
    }
    else
    {
        cout << "chmcyl delete shm sucess,shmid:" << shmid << endl;
    }
}

void DebugShm(int shmid)
{
    shmid_ds shmds;
    int n = shmctl(shmid,IPC_STAT,&shmds);
    if(n < 0)
    {
        cerr << "shmctl error" << endl;
        return;
    }

    cout << "shmds.shm_segsz: " << shmds.shm_segsz << endl;
    cout << "shmds.shm_nattch: " << shmds.shm_nattch << endl;
    cout << "shmds.shm_ctime: " << shmds.shm_ctime << endl;
    cout << "shmds.shm_perm.__key: " << shmds.shm_perm.__key << endl;
}

void* ShmAttach(int shmid)
{
    void* addr = shmat(shmid,nullptr,0);
    if((long long int) addr == -1)
    {
        cerr << "ShmAttach error" << endl;
        return nullptr;
    }
    return addr;
}


void ShDetach(void* addr)
{
    int n = shmdt(addr);
    if(n < 0)
    {
        cerr << "ShDetach error" << endl;
    }
}



